<template>
    <el-form :model="form" label-width="120px">
        <el-form-item label="角色名称">
            <el-input v-model="name" />
        </el-form-item>
        <el-form-item label="角色权限">
            <el-tree ref="treeRef" :data="menus" show-checkbox  node-key="id" highlight-current
                :props="defaultProps" />
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="handleSubmit">提交</el-button>
            <el-button>重置</el-button>
        </el-form-item>
    </el-form>
</template>

<script>
import { rolePost } from "../../api/user";
import { routes } from "../../router/index";
export default {
    data() {
        return {
            name: "",
            menus: [], //用来渲染tree组件的数据包
            defaultProps: {
                label: (data, node) => {
                    //配置tree组件渲染时的标题文字
                    // console.log(data.meta.label);
                    return data.meta.label;
                },
            },
            roleCheckMenu: [], //存放用户勾选的tree数据
        };
    },
    methods: {
        handleSubmit() {
            this.getCheckedTree();
            rolePost({
                //向数据库新增角色
                name: this.name,
                roleCheckMenu: this.roleCheckMenu,
            });
        },
        initMenus() {
            //将路由配置数据包中，渲染菜单的部分路由配置提取出来
            this.menus = routes[0].children;
        },
        getCheckedTree() {
            //调用此函数可以提取被勾选的tree组件数据
            // console.log(this.$refs);
            let checked = this.$refs.treeRef.getCheckedNodes(true); //获取被勾选的tree节点
            // console.log(checked);
            let tempList = [
                // '轮播管理','产品管理'
            ]; //临时记录一下，父级label
            let result = []; //存放最终需要提交到数据库的结果
            checked.forEach((item) => {
                //item子对象
                let parant = this.menus.find((itm) => {
                    //itm时第一层对象
                    return itm.children.some((child) => item.path == child.path);
                });
                // parant 是期望找到，被勾选的checked元素所对应的父级
                if (!tempList.includes(parant.meta.label)) {
                    tempList.push(parant.meta.label);
                    result.push({
                        path: parant.path,
                        component: parant.component,
                        meta: parant.meta,
                        children: [item],
                    });
                } else {
                    //归属于同一个父级的子集，走else
                    result.find((res) => parant.path == res.path).children.push(item);
                }
                // console.log(parant);
            });
            console.log(tempList, result);
            this.roleCheckMenu = result; //将处理好的数据结果，存入data
        },
    },
    created() {
        this.initMenus();
    },
};
</script>

<style lang="scss" scoped>

</style>
